import * as THREE from './three.min.js'

/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author erich666 / http://erichaines.com
 */
/*global THREE, console */

// This set of controls performs orbiting, dollying (zooming), and panning. It maintains
// the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is
// supported.
//
//    Orbit - left mouse / touch: one finger move
//    Zoom - middle mouse, or mousewheel / touch: two finger spread or squish
//    Pan - right mouse, or arrow keys / touch: three finter swipe
//
// This is a drop-in replacement for (most) TrackballControls used in examples.
// That is, include this js file and wherever you see:
//    	controls = new THREE.TrackballControls( camera );
//      controls.target.z = 150;
// Simple substitute "OrbitControls" and the control should work as-is.

THREE.OrbitControls = function (object, domElement) {

    this.object = object;
    this.domElement = (domElement !== undefined) ? domElement : document;

    // API

    // Set to false to disable this control
    this.enabled = true;

    // "target" sets the location of focus, where the control orbits around
    // and where it pans with respect to.
    this.target = new THREE.Vector3();

    // center is old, deprecated; use "target" instead
    this.center = this.target;

    // This option actually enables dollying in and out; left as "zoom" for
    // backwards compatibility
    this.noZoom = false;
    this.zoomSpeed = 1.0;

    // Limits to how far you can dolly in and out
    this.minDistance = 0;
    this.maxDistance = Infinity;

    // Set to true to disable this control
    this.noRotate = false;
    this.rotateSpeed = 1.0;

    // Set to true to disable this control
    this.noPan = false;
    this.keyPanSpeed = 7.0; // pixels moved per arrow key push

    // Set to true to automatically rotate around the target
    this.autoRotate = false;
    this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60

    // How far you can orbit vertically, upper and lower limits.
    // Range is 0 to Math.PI radians.
    this.minPolarAngle = 0; // radians
    this.maxPolarAngle = Math.PI; // radians

    // How far you can orbit horizontally, upper and lower limits.
    // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
    this.minAzimuthAngle = -Infinity; // radians
    this.maxAzimuthAngle = Infinity; // radians

    // Set to true to disable use of the keys
    this.noKeys = false;

    // The four arrow keys
    this.keys = {
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        BOTTOM: 40
    };

    // Mouse buttons
    this.mouseButtons = {
        ORBIT: THREE.MOUSE.LEFT,
        ZOOM: THREE.MOUSE.MIDDLE,
        PAN: THREE.MOUSE.RIGHT
    };

    ////////////
    // internals

    var scope = this;

    var EPS = 0.000001;

    var rotateStart = new THREE.Vector2();
    var rotateEnd = new THREE.Vector2();
    var rotateDelta = new THREE.Vector2();

    var panStart = new THREE.Vector2();
    var panEnd = new THREE.Vector2();
    var panDelta = new THREE.Vector2();
    var panOffset = new THREE.Vector3();

    var offset = new THREE.Vector3();

    var dollyStart = new THREE.Vector2();
    var dollyEnd = new THREE.Vector2();
    var dollyDelta = new THREE.Vector2();

    var theta;
    var phi;
    var phiDelta = 0;
    var thetaDelta = 0;
    var scale = 1;
    var pan = new THREE.Vector3();

    var lastPosition = new THREE.Vector3();
    var lastQuaternion = new THREE.Quaternion();

    var STATE = {
        NONE: -1,
        ROTATE: 0,
        DOLLY: 1,
        PAN: 2,
        TOUCH_ROTATE: 3,
        TOUCH_DOLLY: 4,
        TOUCH_PAN: 5
    };

    var state = STATE.NONE;

    // for reset

    this.target0 = this.target.clone();
    this.position0 = this.object.position.clone();

    // so camera.up is the orbit axis

    var quat = new THREE.Quaternion().setFromUnitVectors(object.up, new THREE.Vector3(0, 1, 0));
    var quatInverse = quat.clone().inverse();

    // events

    var changeEvent = {
        type: 'change'
    };
    var startEvent = {
        type: 'start'
    };
    var endEvent = {
        type: 'end'
    };

    this.rotateLeft = function (angle) {

        if (angle === undefined) {

            angle = getAutoRotationAngle();

        }

        thetaDelta -= angle;

    };

    this.rotateUp = function (angle) {

        if (angle === undefined) {

            angle = getAutoRotationAngle();

        }

        phiDelta -= angle;

    };

    // pass in distance in world space to move left
    this.panLeft = function (distance) {

        var te = this.object.matrix.elements;

        // get X column of matrix
        panOffset.set(te[0], te[1], te[2]);
        panOffset.multiplyScalar(-distance);

        pan.add(panOffset);

    };

    // pass in distance in world space to move up
    this.panUp = function (distance) {

        var te = this.object.matrix.elements;

        // get Y column of matrix
        panOffset.set(te[4], te[5], te[6]);
        panOffset.multiplyScalar(distance);

        pan.add(panOffset);

    };

    // pass in x,y of change desired in pixel space,
    // right and down are positive
    this.pan = function (deltaX, deltaY) {

        var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

        if (scope.object.fov !== undefined) {

            // perspective
            var position = scope.object.position;
            var offset = position.clone().sub(scope.target);
            var targetDistance = offset.length();

            // half of the fov is center to top of screen
            targetDistance *= Math.tan((scope.object.fov / 2) * Math.PI / 180.0);

            // we actually don't use screenWidth, since perspective camera is fixed to screen height
            scope.panLeft(2 * deltaX * targetDistance / element.clientHeight);
            scope.panUp(2 * deltaY * targetDistance / element.clientHeight);

        } else if (scope.object.top !== undefined) {

            // orthographic
            scope.panLeft(deltaX * (scope.object.right - scope.object.left) / element.clientWidth);
            scope.panUp(deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight);

        } else {

            // camera neither orthographic or perspective
            console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');

        }

    };

    this.dollyIn = function (dollyScale) {

        if (dollyScale === undefined) {

            dollyScale = getZoomScale();

        }

        scale /= dollyScale;

    };

    this.dollyOut = function (dollyScale) {

        if (dollyScale === undefined) {

            dollyScale = getZoomScale();

        }

        scale *= dollyScale;

    };

    this.update = function () {

        var position = this.object.position;

        offset.copy(position).sub(this.target);

        // rotate offset to "y-axis-is-up" space
        offset.applyQuaternion(quat);

        // angle from z-axis around y-axis

        theta = Math.atan2(offset.x, offset.z);

        // angle from y-axis

        phi = Math.atan2(Math.sqrt(offset.x * offset.x + offset.z * offset.z), offset.y);

        if (this.autoRotate && state === STATE.NONE) {

            this.rotateLeft(getAutoRotationAngle());

        }

        theta += thetaDelta;
        phi += phiDelta;

        // restrict theta to be between desired limits
        theta = Math.max(this.minAzimuthAngle, Math.min(this.maxAzimuthAngle, theta));

        // restrict phi to be between desired limits
        phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, phi));

        // restrict phi to be betwee EPS and PI-EPS
        phi = Math.max(EPS, Math.min(Math.PI - EPS, phi));

        var radius = offset.length() * scale;

        // restrict radius to be between desired limits
        radius = Math.max(this.minDistance, Math.min(this.maxDistance, radius));

        // move target to panned location
        this.target.add(pan);

        offset.x = radius * Math.sin(phi) * Math.sin(theta);
        offset.y = radius * Math.cos(phi);
        offset.z = radius * Math.sin(phi) * Math.cos(theta);

        // rotate offset back to "camera-up-vector-is-up" space
        offset.applyQuaternion(quatInverse);

        position.copy(this.target).add(offset);

        this.object.lookAt(this.target);

        thetaDelta = 0;
        phiDelta = 0;
        scale = 1;
        pan.set(0, 0, 0);

        // update condition is:
        // min(camera displacement, camera rotation in radians)^2 > EPS
        // using small-angle approximation cos(x/2) = 1 - x^2 / 8

        if (lastPosition.distanceToSquared(this.object.position) > EPS ||
            8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS) {

            this.dispatchEvent(changeEvent);

            lastPosition.copy(this.object.position);
            lastQuaternion.copy(this.object.quaternion);

        }

    };


    this.reset = function () {

        state = STATE.NONE;

        this.target.copy(this.target0);
        this.object.position.copy(this.position0);

        this.update();

    };

    this.getPolarAngle = function () {

        return phi;

    };

    this.getAzimuthalAngle = function () {

        return theta

    };

    function getAutoRotationAngle() {

        return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;

    }

    function getZoomScale() {

        return Math.pow(0.95, scope.zoomSpeed);

    }

    function onMouseDown(event) {

        if (scope.enabled === false) return;
        event.preventDefault();

        if (event.button === scope.mouseButtons.ORBIT) {
            if (scope.noRotate === true) return;

            state = STATE.ROTATE;

            rotateStart.set(event.clientX, event.clientY);

        } else if (event.button === scope.mouseButtons.ZOOM) {
            if (scope.noZoom === true) return;

            state = STATE.DOLLY;

            dollyStart.set(event.clientX, event.clientY);

        } else if (event.button === scope.mouseButtons.PAN) {
            if (scope.noPan === true) return;

            state = STATE.PAN;

            panStart.set(event.clientX, event.clientY);

        }

        if (state !== STATE.NONE) {
            document.addEventListener('mousemove', onMouseMove, false);
            document.addEventListener('mouseup', onMouseUp, false);
            scope.dispatchEvent(startEvent);
        }

    }

    function onMouseMove(event) {

        if (scope.enabled === false) return;

        event.preventDefault();

        var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

        if (state === STATE.ROTATE) {

            if (scope.noRotate === true) return;

            rotateEnd.set(event.clientX, event.clientY);
            rotateDelta.subVectors(rotateEnd, rotateStart);

            // rotating across whole screen goes 360 degrees around
            scope.rotateLeft(2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed);

            // rotating up and down along whole screen attempts to go 360, but limited to 180
            scope.rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed);

            rotateStart.copy(rotateEnd);

        } else if (state === STATE.DOLLY) {

            if (scope.noZoom === true) return;

            dollyEnd.set(event.clientX, event.clientY);
            dollyDelta.subVectors(dollyEnd, dollyStart);

            if (dollyDelta.y > 0) {

                scope.dollyIn();

            } else {

                scope.dollyOut();

            }

            dollyStart.copy(dollyEnd);

        } else if (state === STATE.PAN) {

            if (scope.noPan === true) return;

            panEnd.set(event.clientX, event.clientY);
            panDelta.subVectors(panEnd, panStart);

            scope.pan(panDelta.x, panDelta.y);

            panStart.copy(panEnd);

        }

        if (state !== STATE.NONE) scope.update();

    }

    function onMouseUp( /* event */ ) {

        if (scope.enabled === false) return;

        document.removeEventListener('mousemove', onMouseMove, false);
        document.removeEventListener('mouseup', onMouseUp, false);
        scope.dispatchEvent(endEvent);
        state = STATE.NONE;

    }

    function onMouseWheel(event) {

        if (scope.enabled === false || scope.noZoom === true || state !== STATE.NONE) return;

        event.preventDefault();
        event.stopPropagation();

        var delta = 0;

        if (event.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9

            delta = event.wheelDelta;

        } else if (event.detail !== undefined) { // Firefox

            delta = -event.detail;

        }

        if (delta > 0) {

            scope.dollyOut();

        } else {

            scope.dollyIn();

        }

        scope.update();
        scope.dispatchEvent(startEvent);
        scope.dispatchEvent(endEvent);

    }

    function onKeyDown(event) {

        if (scope.enabled === false || scope.noKeys === true || scope.noPan === true) return;

        switch (event.keyCode) {

            case scope.keys.UP:
                scope.pan(0, scope.keyPanSpeed);
                scope.update();
                break;

            case scope.keys.BOTTOM:
                scope.pan(0, -scope.keyPanSpeed);
                scope.update();
                break;

            case scope.keys.LEFT:
                scope.pan(scope.keyPanSpeed, 0);
                scope.update();
                break;

            case scope.keys.RIGHT:
                scope.pan(-scope.keyPanSpeed, 0);
                scope.update();
                break;

        }

    }

    function touchstart(event) {

        if (scope.enabled === false) return;

        switch (event.touches.length) {

            case 1: // one-fingered touch: rotate

                if (scope.noRotate === true) return;

                state = STATE.TOUCH_ROTATE;

                rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
                break;

            case 2: // two-fingered touch: dolly

                if (scope.noZoom === true) return;

                state = STATE.TOUCH_DOLLY;

                var dx = event.touches[0].pageX - event.touches[1].pageX;
                var dy = event.touches[0].pageY - event.touches[1].pageY;
                var distance = Math.sqrt(dx * dx + dy * dy);
                dollyStart.set(0, distance);
                break;

            case 3: // three-fingered touch: pan

                if (scope.noPan === true) return;

                state = STATE.TOUCH_PAN;

                panStart.set(event.touches[0].pageX, event.touches[0].pageY);
                break;

            default:

                state = STATE.NONE;

        }

        if (state !== STATE.NONE) scope.dispatchEvent(startEvent);

    }

    function touchmove(event) {

        if (scope.enabled === false) return;

        event.preventDefault();
        event.stopPropagation();

        var element = scope.domElement === document ? scope.domElement.body : scope.domElement;

        switch (event.touches.length) {

            case 1: // one-fingered touch: rotate

                if (scope.noRotate === true) return;
                if (state !== STATE.TOUCH_ROTATE) return;

                rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
                rotateDelta.subVectors(rotateEnd, rotateStart);

                // rotating across whole screen goes 360 degrees around
                scope.rotateLeft(2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed);
                // rotating up and down along whole screen attempts to go 360, but limited to 180
                scope.rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed);

                rotateStart.copy(rotateEnd);

                scope.update();
                break;

            case 2: // two-fingered touch: dolly

                if (scope.noZoom === true) return;
                if (state !== STATE.TOUCH_DOLLY) return;

                var dx = event.touches[0].pageX - event.touches[1].pageX;
                var dy = event.touches[0].pageY - event.touches[1].pageY;
                var distance = Math.sqrt(dx * dx + dy * dy);

                dollyEnd.set(0, distance);
                dollyDelta.subVectors(dollyEnd, dollyStart);

                if (dollyDelta.y > 0) {

                    scope.dollyOut();

                } else {

                    scope.dollyIn();

                }

                dollyStart.copy(dollyEnd);

                scope.update();
                break;

            case 3: // three-fingered touch: pan

                if (scope.noPan === true) return;
                if (state !== STATE.TOUCH_PAN) return;

                panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
                panDelta.subVectors(panEnd, panStart);

                scope.pan(panDelta.x, panDelta.y);

                panStart.copy(panEnd);

                scope.update();
                break;

            default:

                state = STATE.NONE;

        }

    }

    function touchend( /* event */ ) {

        if (scope.enabled === false) return;

        scope.dispatchEvent(endEvent);
        state = STATE.NONE;

    }

    this.domElement.addEventListener('contextmenu', function (event) {
        event.preventDefault();
    }, false);
    this.domElement.addEventListener('mousedown', onMouseDown, false);
    this.domElement.addEventListener('mousewheel', onMouseWheel, false);
    this.domElement.addEventListener('DOMMouseScroll', onMouseWheel, false); // firefox

    this.domElement.addEventListener('touchstart', touchstart, false);
    this.domElement.addEventListener('touchend', touchend, false);
    this.domElement.addEventListener('touchmove', touchmove, false);

    window.addEventListener('keydown', onKeyDown, false);

    // force an update at start
    this.update();

};

THREE.OrbitControls.prototype = Object.create(THREE.EventDispatcher.prototype);
THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;



window.THREE = THREE
var container;

var camera, scene, controls;
var raycaster = new THREE.Raycaster();

var renderer;

var clock = new THREE.Clock();
var time = 0;
var duration = 100;
var keyframes = 4;
var interpolation = duration / keyframes;
var currentKeyframe = 0;
var lastKeyframe = 0;
var animOffset = 1;
var radius = 600;
var theta = 0;
var prevTime = Date.now();

var lamp_light, light, fake_light;

var video, videoImage, videoImageContext, videoTexture;

var mouseX = 0,
    mouseY = 0;


var mesh, circle, controller_animation, helper;
var morph_logic;

var screen_mesh;
var texture1;
var base = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/61062/";
var tv_screen, tv_context;
var å = {
    ready: {
        count: 0
    },
    colors: {
        blank: 0xffffff
    },
    mouse: {
        x: 0,
        y: 0,
        z: 0.5
    },
    models: {
        couch: base + "couch.json",
        monitor: base + "tv_monitor.json",
        tv: base + "tv.json2",
        lamp: base + "lamp_.json",
        kid: base + "little_kid.json",
    },
    targetList: []
}
console.log(762)
console.log(å.models.couch);

//___________________________________________

function generate_color(x, y, z) {
    if (x < 1) {
        x += .01;
    } else {
        x = 0;
    }
    if (y < 1) {
        y += .01;
    } else {
        y = 0;
    }
    if (z < 1) {
        z += .01;
    } else {
        z = 0;
    }

    return [x, y, z];
}

function getRandomColor() {
    var letters = '0123433333000ccc'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }

    return color;
}

var baseMaterial = new THREE.MeshLambertMaterial({
    color: å.colors.blank,
    shading: THREE.FlatShading,
    side: THREE.DoubleSide,
    //map: couch_texture
})

//___________________________________________ KICK IT OFF
// init();
// animate();

//___________________________________________ INIT
export function init(container) {
    // container = document.querySelector('.container');
    console.log(809,container);
    camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, .1, 10000);
    camera.position.x = -305;
    camera.position.y = 55;
    camera.position.z = -65;
    camera.move_direction = 1;
    scene = new THREE.Scene();
    //scene.fog = new THREE.FogExp2( 0x000000, 0.015 );
    å.ready.count++;
    scene.add(camera);

    //___________________________________________ CONTROLS
    controls = new THREE.OrbitControls(camera);
    controls.damping = 0.2;
    controls.addEventListener('change', render);
    controls.maxPolarAngle = Math.PI / 2;
    camera.lookAt(new THREE.Vector3(0, 50, 0));
    controls.target = new THREE.Vector3(0, 50, 0);

    å.ready.count++;

    //___________________________________________ HEMI

    var ambient = new THREE.AmbientLight(0x111111);

    scene.add(ambient);
    // TV
    light = new THREE.SpotLight(0x1A5970, 2);
    light.position.set(15, 15, 68).multiplyScalar(1);
    scene.add(light);

    //___________________________________________ FAKE LIGHT
    fake_light = new THREE.SpotLight(0x1A5970, 15, 200, Math.PI / 2);
    fake_light.position.set(15, 150, 268).multiplyScalar(1);
    scene.add(fake_light);

    fake_light.castShadow = true;

    fake_light.shadowMapWidth = 1024 * 2;
    fake_light.shadowMapHeight = 1024 * 2;

    fake_light.target.position.set(-20, 20, -50);
    fake_light.target.updateMatrixWorld();

    var d = 350;
    fake_light = new THREE.SpotLight(0xF0C043, 2);
    fake_light.shadowCameraLeft = -d;
    fake_light.shadowCameraRight = d;
    fake_light.shadowCameraTop = d * 2.8;
    fake_light.shadowCameraBottom = -d;
    fake_light.shadowCameraNear = 0.01;


    å.ready.count++;
    // LAMP
    lamp_light = new THREE.SpotLight(0xF0C043, .25);
    lamp_light.position.set(-55, 50, -50).multiplyScalar(1);
    scene.add(lamp_light);
    lamp_light.target.position.set(-55, 0, -50);
    lamp_light.target.updateMatrixWorld();

    å.ready.count++;

    // RENDERER

    renderer = new THREE.WebGLRenderer({
        antialias: true,
        transparent: true,
        alpha: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);


    renderer.shadowMapEnabled = true;

    å.ready.count++;
    //__________________________________ LOAD MODEL


    var loader = new THREE.JSONLoader(true);
    loader.load(å.models.couch, function (geometry) {

        couch = new THREE.Mesh(geometry, baseMaterial);

        couch.scale.set(20, 20, 20);

        couch.receiveShadow = true;
        couch.castShadow = true;
        couch.position.y = -20;
        scene.add(couch);

        å.ready.count++;
    });

    var loader = new THREE.JSONLoader(true);
    loader.load(å.models.monitor, function (geometry) {

        tv_monitor = new THREE.Mesh(geometry, baseMaterial);

        tv_monitor.scale.set(20, 20, 20);

        tv_monitor.receiveShadow = true;
        //tv_monitor.castShadow = true;
        tv_monitor.position.y = -20;
        scene.add(tv_monitor);

        å.ready.count++;
    });

    //___________________________________________ TV SCREEN

    var errorCallback = function (e) {
        console.log('Nope!', e);
    };

    video = document.getElementById('myVideo');
    navigator.getUserMedia = navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia;

    if (navigator.getUserMedia) {
        navigator.getUserMedia({
            audio: false,
            video: true
        }, function (stream) {
            video.src = window.URL.createObjectURL(stream);
        }, errorCallback);
    } else {
        video.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/61062/rin-SD.mp4';
    }

    videoImage = document.createElement('canvas');
    videoImage.width = 640;
    videoImage.height = 320;
    videoImageContext = videoImage.getContext('2d');
    videoImageContext.fillStyle = '#ffffff';
    videoImageContext.fillRect(0, 0, videoImage.width, videoImage.height);

    videoTexture = new THREE.Texture(videoImage);
    videoTexture.crossOrigin = "Anonymous";
    videoTexture.minFilter = THREE.LinearFilter;
    videoTexture.magFilter = THREE.LinearFilter;

    loader.load(å.models.tv, function (geometry) {
        var material = new THREE.MeshBasicMaterial({
            color: å.colors.blank,
            map: videoTexture,
            overdraw: true,
            side: THREE.DoubleSide
        });

        var uvs = geometry.faceVertexUvs[0];
        uvs[0][0].set(0, 0);
        uvs[0][1].set(1, 0);
        uvs[0][2].set(1, 1);

        uvs[1][0].set(1, 0);
        uvs[1][1].set(1, 1);
        uvs[1][2].set(0, 1);
        screen_mesh = new THREE.Mesh(geometry, material);
        screen_mesh.scale.set(20, 20, 20);
        screen_mesh.position.y = -20;
        scene.add(screen_mesh);

        å.ready.count++;
    });
    //___________________________________________ Lamp
    loader.load(å.models.lamp, function (geometry, material) {

        screen = new THREE.Mesh(geometry, baseMaterial);
        screen.scale.set(20, 20, 20);
        screen.receiveShadow = true;
        screen.castShadow = true;
        screen.position.y = -20;
        scene.add(screen);
        å.ready.count++;
    });
    //___________________________________________ Little Kid

    loader.load(å.models.kid, function (geometry) {

        var kid_material = new THREE.MeshLambertMaterial({
            color: å.colors.blank,
            shading: THREE.FlatShading,
            morphTargets: true,
            //map: kid_texture
        });
        little_kid = new THREE.SkinnedMesh(geometry, kid_material);

        little_kid.scale.set(20, 20, 20);

        little_kid.receiveShadow = true;
        little_kid.castShadow = true;
        little_kid.position.y = -20;
        scene.add(little_kid);


        animation = new THREE.MorphAnimation(little_kid);
        animation.duration = 500;
        morph_logic = new Logic(little_kid);

        å.ready.count++;
    });

    //___________________________________________ Camera Driver

    var radius = 250;
    var segments = 32;

    var circleGeometry = new THREE.CircleGeometry(radius, segments);
    circle = new THREE.Mesh(circleGeometry);
    //circle.rotation.x = 90 * Math.PI / 180;
    circle.add(camera);
    circle.visible = false;
    scene.add(circle);

    circle.update = function (time) {
        this.rotation.y += .003;
    }

    å.ready.count++;

    //___________________________________________ DUST


    var particles = new THREE.Geometry();
    var pMaterial = new THREE.PointCloudMaterial({
        color: 0xffffff,
        size: 1,
        transparent: true,
        opacity: .25,
        // map : particle_texture
    });
    for (var i = 0; i < 500; i++) {
        var x = (Math.random() - 0.5) * Math.sin(i) * 200;
        var y = (Math.random() - 0.5) * Math.cos(i) * 200;
        var z = (Math.random() - 0.5) * Math.sin(i) * 200;
        particles.vertices.push(new THREE.Vector3(x, y, z));
    }
    var particleSystem_1 = new THREE.PointCloud(particles, pMaterial);
    scene.add(particleSystem_1);

    å.ready.count++;

    //___________________________________________ BOOKSHELF
    var book_shelf = new THREE.Object3D();
    var book_shelf_geometry = new THREE.BoxGeometry(1.5, 78, 15);

    var book_shelf_l = new THREE.Mesh(book_shelf_geometry, baseMaterial);
    var book_shelf_r = new THREE.Mesh(book_shelf_geometry, baseMaterial);

    book_shelf_l.receiveShadow = true;
    book_shelf_l.castShadow = true;
    book_shelf_l.position.y = 10;

    book_shelf_r.receiveShadow = true;
    book_shelf_r.castShadow = true;
    book_shelf.add(book_shelf_l);
    book_shelf_r.position.x = 32;
    book_shelf_r.position.y = 10;
    book_shelf.add(book_shelf_r);

    var book_shelf_floor_geo = new THREE.BoxGeometry(30, 1.5, 14);
    var book_shelf_floor = new THREE.Mesh(book_shelf_floor_geo, baseMaterial);
    book_shelf_floor.position.x = 16;
    book_shelf_floor.position.z = -.5;

    var shelf_floors = [];
    for (var f = 0; f < 7; f++) {
        shelf_floors[f] = new THREE.Mesh(book_shelf_floor_geo, baseMaterial);

        shelf_floors[f].position.x = 16;
        shelf_floors[f].position.y = -24 + f * 12;
        shelf_floors[f].position.z = -.5;
        shelf_floors[f].receiveShadow = true;
        shelf_floors[f].castShadow = true;
        book_shelf.add(shelf_floors[f]);
    }

    å.ready.count++;

    var books = [];
    var book_geo = new THREE.BoxGeometry(2, 7.5, 10);

    var book_count = 0;
    for (var r = 0; r < 6; r++) {
        for (var b = 0; b < 12; b++) {
            books[book_count] = new THREE.Mesh(book_geo, baseMaterial);
            books[book_count].position.x = 5 + b * 2.25;
            books[book_count].position.y = -20 + r * 12;
            books[book_count].position.z = Math.random() * 2.0;
            books[book_count].rotation.y = Math.random() * .25;
            books[book_count].rotation.z = Math.random() * .05;

            books[book_count].receiveShadow = true;
            books[book_count].castShadow = true;
            book_shelf.add(books[book_count]);
            book_count++;
        }
    }
    book_shelf.position.set(70, 8, -20);
    book_shelf.rotation.y = 90 * Math.PI / 180;

    var second_shelf = book_shelf.clone();
    second_shelf.position.z = 16;
    scene.add(second_shelf);


    scene.add(book_shelf);



    å.ready = true;


} // end of init
// __________________________________ Only for Skinned Mesh Animation
function ensureLoop(animation) {
    for (var i = 0; i < animation.hierarchy.length; i++) {

        var bone = animation.hierarchy[i];
        var first = animation.data.hierarchy[0];
        var last = animation.data.hierarchy[animation.data.hierarchy.length - 1];



        last.pos = first.pos;
        last.rot = first.rot;
        last.scl = first.scl;
    }
}

function clicker(obj) {
    obj.parent.ex_bool = true;
    obj.parent.children.forEach(function (el) {
        explosion = new Explode(el);
    });
}

function Logic(mesh) {
    this.ready = true;
    this.reset_all_morphs = function () {
        for (var i = 0; i < mesh.morphTargetInfluences.length; i++) {
            mesh.morphTargetInfluences[i] = 0;
        }
    }
    var curr = 0;
    this.counter = 0;
    var Presets = [
        'default',
        'eye_closed',
        'laugh',
        'mouth_open'
    ]
    this.set_specific_morph = function (type, intensity) {
        var speed = 0.01;
        switch (type) {
            case 'default':
                this.reset_all_morphs();
                mesh.morphTargetInfluences[0] = intensity * speed;
                break;
            case 'eye_closed':
                this.reset_all_morphs();
                mesh.morphTargetInfluences[1] = intensity * speed;
                break;
            case 'laugh':
                this.reset_all_morphs();
                mesh.morphTargetInfluences[2] = intensity * speed;
                break;
            case 'mouth_open':
                this.reset_all_morphs();
                mesh.morphTargetInfluences[3] = intensity * speed;
                break;
        }
    }
    this.direction = 1;
    this.loop_all_morphs = function (time) {

        if (this.counter % 50 == 0) {
            this.direction *= (-1);
        }
        if (this.counter <= 0) {
            this.direction *= (-1);
            if (curr < Presets.length) {
                curr++;
            } else {
                curr = 0;
            }
        }
        this.set_specific_morph(Presets[curr], this.counter);
        this.counter += 4 * this.direction;
    }

    return;
}


//___________________________________________ Event in Space
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
//___________________________________________ click

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);

}


function onDocumentMouseDown(event) {
    å.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    å.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    // find intersections
    var vector = new THREE.Vector3(å.mouse.x, å.mouse.y, 1);
    vector.unproject(camera);
    var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
    var intersects = ray.intersectObjects(å.targetList);
    if (intersects.length > 0) {
        clicker(intersects[0].object);
    }
}
//___________________________________________ move

function onDocumentMouseMove(event) {
    å.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    å.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
    // find intersections
    var vector = new THREE.Vector3(å.mouse.x, å.mouse.y, 1);
    vector.unproject(camera);
    var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

    var intersects = ray.intersectObjects(å.targetList);

    if (intersects.length > 0) {
        mover(intersects[0].object);
    }
    if (typeof morph_logic != "undefined") {

        morph_logic.loop_all_morphs(time);
    }

}



//___________________________________________ RENDER 


export function animate() {

    requestAnimationFrame(animate);

    render();

}

function render(time) {
    theta += 0.1;
    var delta = .75 * clock.getDelta();


    if (å.ready) {
        circle.update(time);
        videoImageContext.drawImage(video, 0, 0, 640, 320);
        if (videoTexture) {
            videoTexture.needsUpdate = true;
        }
    }

    // update morph

    if (typeof animation !== "undefined") {
        var keyframe = Math.floor(time / interpolation) + animOffset;

        morph_logic.loop_all_morphs(time);

        THREE.AnimationHandler.update(delta / interpolation);

        var time = Date.now();
        prevTime = time;

    }

    camera.lookAt(new THREE.Vector3(0, 20, 0));
    renderer.render(scene, camera);

}